package main

import "strings"

type HTTPWhiteLists struct {
	datas map[string]bool
	dbo   *DBOperation
}

func NewHTTPWhiteLists(dbo *DBOperation) *HTTPWhiteLists {
	wl := HTTPWhiteLists{dbo: dbo}
	wl.datas = map[string]bool{"127.0.0.1": true}
	wl.Init()

	return &wl
}

func (p *HTTPWhiteLists) Init() {
	ips := p.dbo.LoadIPWHiteLists()

	for _, v := range ips {
		p.datas[v] = true
	}

}

func (p *HTTPWhiteLists) List() []string {
	res := make([]string, 0, len(p.datas))
	for k := range p.datas {
		res = append(res, k)
	}
	return res
}

func (p *HTTPWhiteLists) Add(ip string) {
	ip = p.trimIP(ip)

	_, ok := p.datas[ip]
	if !ok {
		p.datas[ip] = true
		p.dbo.IPWhiteListsAdd(ip)
	}
}

func (p *HTTPWhiteLists) Exists(ip string) bool {
	ip = p.trimIP(ip)

	_, ok := p.datas[ip]
	return ok
}

func (p *HTTPWhiteLists) Remove(ip string) {
	ip = p.trimIP(ip)

	_, ok := p.datas[ip]
	if ok {
		delete(p.datas, ip)
		p.dbo.IPWhiteListsRemove(ip)
	}
}

func (p *HTTPWhiteLists) trimIP(ip string) string {
	index := strings.Index(ip, ":")
	if index >= 0 {
		ip = ip[0:index]
	}

	return ip
}
